<template>
    <div style="padding: 0 10px">
        <div class="header">
            <ExchangeHgQueryCondition
                @comReturn="comReturn"
                @handleButton="handleButton"
                :isFirst="isFirst && activeValue === 'exchangeHg'"
            ></ExchangeHgQueryCondition>
        </div>
        <div :class="{ isOpened: isOpen, noOpened: !isOpen }">
            <vxe-table
                :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :data="tableData"
                :key="tableKey + 'tableKey'"
                v-loading="loading"
                border
                stripe
                resizable
                :auto-resize="true"
                show-footer
                :footer-method="getSummaries"
                :sort-config="{
                    defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                    remote: true,
                }"
                highlight-current-row
                @sort-change="changeTableSort"
                :resizable-config="{ minWidth: '60' }"
                ref="table"
                show-header-overflow="tooltip"
                show-footer-overflow="tooltip"
                header-align="center"
            >
                <vxe-column
                    v-for="item in showFieldList"
                    :field="item.id"
                    :title="item.content"
                    :key="item.content"
                    :align="getAlign(item)"
                    :min-width="item.minWidth || '105px'"
                    show-overflow="tooltip"
                    :sortable="item.sortable"
                >
                    <template slot-scope="scope">
                        <span v-if="item.render && typeof item.render === 'function'">
                            {{ item.render(scope.row[item.id], scope.row) || '--' }}
                        </span>
                        <span v-else-if="formatParam.includes(item.id)">
                            {{ numberFormat(scope.row[item.id], 2) || '--' }}
                        </span>
                        <span v-else-if="['actualDays', 'actualDays'].includes(item.id)">
                            {{ scope.row[item.id] + '' == '0' ? 0 : numberFormat(scope.row[item.id]) || '--' }}
                        </span>
                        <span v-else-if="['hgDate', 'redeemLawdate', 'redeemLiquidate', 'settleDate'].includes(item.id)">
                            {{ dateFormat(scope.row[item.id]) }}
                        </span>
                        <span v-else>
                            {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
            <RiskPagination :paging="page" @page-change="pageRet"></RiskPagination>
        </div>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :reset-no-selected-field-list="resetNoSelectedFieldList"
            table-name="TN_EXCHANGE_HG_TEST"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { dateFormat, numberFormat } from '@/utils/tools';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import ExchangeHgQueryCondition from './exchange-hg-query-condition.vue';
import { getTableLayout } from '@/common/api/commonApi';
import { exchangeOnWayHgExport, exchangeOnWayHgList } from '../api/comprehensive-info-query';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({ name: 'ExchangeHg', components: { RiskTableLayout, RiskPagination, ExchangeHgQueryCondition } })
export default class ExchangeHg extends Vue {
    searchParam: any = {}; // 查询条件

    resetNoSelectedFieldList = [];
    numberFormat = numberFormat;
    dateFormat = dateFormat;
    isOpen: boolean = false;

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        {
            content: '业务日期',
            id: 'businessDate',
            align: 'center',
            sortable: false,
        },
        { id: 'fundId', content: '产品序号', align: 'left', sortable: true },
    ];

    tableData: any[] = []; // 表格数据

    tableKey: number = -1;

    loading: boolean = false; // 页面渲染

    private sortProp: string = 'stockCode'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'VC_INTER_CODE ASC'; // 默认排序字段

    private page: pages = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    formatParam = [
        'nowInterest',
        'endDealBalance',
        'redeemInterest',
        'dealPrice',
        'settleSpeed',
        'dealBalance',
        'dealAmountTrade',
        'dealBalanceTrade',
    ];

    tableColumns = [
        {
            content: '业务日期',
            id: 'businessDate',
            align: 'center',
            sortable: false,
            render: (value) => dateFormat(value),
        },
        { id: 'fundId', content: '产品序号', align: 'left', sortable: true },
        { id: 'fundCode', content: '产品编码', align: 'left', sortable: true },
        { id: 'fundName', content: '产品名称', align: 'left', sortable: true },
        { id: 'assetId', content: '资产单元编号', minWidth: '130px', align: 'left', sortable: true },
        { id: 'assetName', content: '资产单元名称', minWidth: '130px', align: 'left', sortable: true },
        { id: 'basecombiId', content: '组合编码', align: 'left', sortable: true },
        { id: 'combiName', content: '组合名称', align: 'left', sortable: true },
        { id: 'stockCode', content: '证券回购代码', minWidth: '130px', align: 'left', sortable: true },
        { id: 'stockNameSt', content: '证券名称', align: 'left', sortable: true },
        { id: 'stockType', content: '证券类别', align: 'center', sortable: true },
        // 资产分类
        { id: 'marketName', content: '交易市场', align: 'center', sortable: true },
        { id: 'entrustDirection', content: '委托方向', align: 'center', sortable: true },
        { id: 'dealAmountTrade', content: '数量', sortable: true },
        { id: 'dealBalanceTrade', content: '净资金额', sortable: true },
        { id: 'dealBalance', content: '首期成交金额', minWidth: '130px', sortable: true },
        { id: 'hgDate', content: '交易日期', align: 'center', sortable: true },
        // 首期结算日
        { id: 'redeemLawdate', content: '法定购回日期', minWidth: '130px', align: 'center', sortable: true },
        { id: 'redeemLiquidate', content: '实际购回日期', minWidth: '130px', align: 'center', sortable: true },
        { id: 'settleSpeed', content: '清算速度', sortable: true },
        { id: 'settleDate', content: '购回交割日期', minWidth: '130px', align: 'center', sortable: true },
        { id: 'redeemDays', content: '回购天数', sortable: true },
        { id: 'actualDays', content: '实际占款天数', minWidth: '130px', sortable: true },
        { id: 'dealPrice', content: '回购利率(%)', minWidth: '130px', sortable: true },
        { id: 'redeemInterest', content: '回购利息', sortable: true },
        { id: 'endDealBalance', content: '到期成交金额', minWidth: '130px', sortable: true },
        { id: 'nowInterest', content: '计提利息', sortable: true },
    ];

    // 排序字段
    sortableObj = {
        fundId: 'L_FUND_ID',
        fundCode: 'VC_FUND_CODE',
        fundName: 'VC_FUND_NAME',
        assetId: 'L_ASSET_ID',
        assetName: 'VC_ASSET_NAME',
        basecombiId: 'L_BASECOMBI_ID',
        combiName: 'VC_COMBI_NAME',
        stockCode: 'VC_INTER_CODE',
        stockNameSt: 'VC_STOCK_NAME',
        stockType: 'C_STOCK_TYPE_CODE',
        entrustDirection: 'C_ENTRUST_DIRECTION_CODE',
        hgDate: 'L_HG_DATE',
        redeemLawdate: 'L_REDEEM_LAWDATE',
        redeemLiquidate: 'L_REDEEM_LIQUIDATE',
        settleSpeed: 'L_SETTLE_SPEED',
        settleDate: 'L_SETTLE_DATE',
        redeemDays: 'L_REDEEM_DAYS',
        dealBalance: 'EN_DEAL_BALANCE',
        dealPrice: 'EN_DEAL_PRICE',
        redeemInterest: 'EN_REDEEM_INTEREST',
        nowInterest: 'EN_NOW_INTEREST',
        marketName: 'VC_MARKET_NAME',
        endDealBalance: 'endDealBalance',
        actualDays: 'actualDays',
        dealAmountTrade: 'dealAmountTrade',
        dealBalanceTrade: 'dealBalanceTrade',
    };
    summary: any = {}; // 汇总行
    isFirst: boolean = true;

    @Prop() activeValue: string;

    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'exchangeHg') {
            if (this.isFirst) {
                await this.queryLayout();
                this.getExchangeOnWayHgTableData();
                this.isFirst = false;
            }
        }
    }

    // 分页
    pageRet() {
        this.getExchangeOnWayHgTableData();
    }

    // 获取表格数据
    getExchangeOnWayHgTableData() {
        this.loading = true;
        exchangeOnWayHgList({
            paging: this.page,
            sort: this.sort,
            ...this.searchParam,
        })
            .then((res: any) => {
                if (res.total) {
                    this.summary = res.list[res.list.length - 1];
                    this.tableData = res.list.slice(0, res.list.length - 1);
                } else {
                    this.summary = {};
                    this.tableData = [];
                }
                this.page.total = res.total;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 分页
    pageChange(curPage: number) {
        this.page.currentPage = curPage;
        this.getExchangeOnWayHgTableData();
    }

    // 合计行
    getSummaries() {
        let arr = [];
        if (this.tableData.length) {
            let count = 0;
            let obj = this.tableData[0];
            let objR = this.summary;
            for (let item of this.showFieldList) {
                if (objR[item.id]) {
                    arr[count++] = numberFormat(objR[item.id], 2);
                } else {
                    arr[count++] = '--';
                }
            }
        }
        return [arr];
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            getTableLayout('TN_EXCHANGE_HG_TEST')
                .then((res: any) => {
                    resolve(res);
                })
                .catch((err) => {
                    reject(err);
                });
        });

        if (!resList) {
            // 新用户初始化
            const keys = this.resetNoSelectedFieldList.map((item) => item.id);
            this.showFieldList = this.tableColumns.filter((item) => !keys.includes(item.id));
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.showFieldList = this.fixedFieldList;
            } else {
                this.showFieldList = this.fixedFieldList.concat(JSON.parse(resList));
                // const temps = this.fixedFieldList.concat(JSON.parse(resList)).map(item => item.id);
                // this.showFieldList = this.tableColumns.filter(item => temps.includes(item.id));
            }
        }
        const fixKeys = this.fixedFieldList.map((item) => item.id);
        this.selectedFieldList = this.showFieldList.filter((item) => !fixKeys.includes(item.id));
        this.tableKey++;
    }

    // 对齐方式
    getAlign(ele) {
        let obj = this.tableColumns.find((item) => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }

    // 查询返回
    comReturn(obj) {
        this.isOpen = obj.isOpen;
        this.searchParam = obj.searchParam;
    }

    // 按钮点击回调
    handleButton(type): void {
        if (type == 'search') {
            this.pageChange(1);
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        } else if (type == 'currentLoadout' || type == 'allLoadout') {
            let datas = [];
            if (type == 'currentLoadout') {
                datas = this.tableData;
            }
            exchangeOnWayHgExport({
                data: datas,
                searchVo: this.searchParam,
            });
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/project/pyaxa/pages/report/styles/common';
// 资产查询中的未展开表格高度
.isOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 340px);
    }
}
</style>
